var laydate, table, form;
var projectTable;
layui.use(['form', 'table', 'laydate'], function () {
    form = layui.form,
        table = layui.table,
        laydate = layui.laydate;

    //日期范围
    laydate.render({
        elem: '#date-range'
        , range: true
    });
    //全局设置table、
    table.set({
        request: {
            pageName: 'currentPage', //页码的参数名称，默认：page
            limitName: 'pageSize',
        },
        response: {
            statusName: 'code' //数据状态的字段名称，默认：code
            , statusCode: '000000' //成功的状态码，默认：0
            , msgName: 'msg' //状态信息的字段名称，默认：msg
            , countName: 'total' //数据总数的字段名称，默认：count
            , dataName: 'rows' //数据列表的字段名称，默认：data
        },
        limits: [10, 15, 20, 25, 50, 100],
        limit: 10,
        page: true
    });
    fileList.init();
});

var fileList = {
    init: function () {
        // 监听回车
        ad.keydown.enter('search');
        // 初始化
        fileList.initTable.load();

        // 监听搜索操作
        form.on('submit(data-search-btn)', function (data) {
            //执行搜索重载
            fileList.reload();
            return false;
        });

        /**
         * toolbar监听事件
         */
        table.on('toolbar(currentTableFilter)', function (obj) {
            var checkStatus = table.checkStatus(obj.config.id);
            var data = checkStatus.data;
            var i;
            if (obj.event === 'add') {  // 监听添加操作
                layer.open({
                    title: '文件上传',
                    type: 2,
                    shade: 0.2,
                    maxmin: true,
                    shadeClose: true,
                    area: ['100%', '100%'],
                    content: baseUrl + 'file/add?projectId=' + $('#projectId').val(),
                    end: function () {
                        fileList.reload();
                        layer.msg('处理成功');
                    }
                });
            } else if (obj.event === 'delete') {
                if (data) {
                    var ids = '';
                    for (i = 0; i < data.length; i ++) {
                        ids += data[i].fileId + ',';
                    }
                    globalObj.delFile(ids);
                }
            } else if (obj.event === 'zip') {
                if (data) {
                    var urls = '';
                    for (i = 0; i < data.length; i ++) {
                        urls += data[i].url + ',';
                    }
                    globalObj.zipFile(urls);
                }
            } else if (obj.event === 'tips') {
                layer.msg('"文件说明"可直接在表格处修改！')
            }
        });

        table.on('edit(currentTableFilter)', function (obj) {
            var value = obj.value //得到修改后的值
                ,data = obj.data; //得到所在行所有键值
            globalObj.editRemark(data.fileId, value);
        })
    },

    initTable: {
        load: function() {
            if (projectTable) {
                fileList.reload();
            }
            projectTable = table.render({
                elem: '#currentTableId',
                url: baseUrl + 'file/getList',
                toolbar: '#toolbarDemo',
                defaultToolbar: ['filter', 'exports', 'print', { //自定义头部工具栏右侧图标。如无需自定义，去除该参数即可
                    title: '提示'
                    ,layEvent: 'tips'
                    ,icon: 'layui-icon-tips'
                }],
                cols: [[
                    {type: "checkbox", width: 50, fixed: "left"},
                    {field: 'fileName', title: '文件名'},
                    {field: 'size', title: '大小'},
                    {field: 'uploadDate', title: '上传日期', templet: "#uploadDate"},
                    {field: 'remark', title: '文件说明', edit: 'text'},
                    {field: 'url', title: '下载地址', templet: '#fileUrl'}
                ]],
                where: ad.common.formToJson('fileForm')
            });
        }
    },

    reload: function() {
        table.reload('currentTableId', {
            where: ad.common.formToJson('fileForm')
        });
    }
};

var globalObj = globalObj || {};
globalObj = $.extend(globalObj, {
    delFile: function (ids) {
        (new globalObj.Request(globalObj.url)).setParams({
            param: {
                fileId: ids
            },
            serviceId: "app.file.delete"
        }).do().success(function (data) {
            fileList.reload();
            layer.msg('处理成功');
        });
    },
    zipFile: function (urls) {
        (new globalObj.Request(globalObj.url)).setParams({
            param: {
                filePaths: urls
            },
            serviceId: "app.file.zipBySelect"
        }).do().success(function (data) {
            // 下载返回地址
            downloadZip(data);
        });
    },
    editRemark: function (fileId, remark) {
        (new globalObj.Request(globalObj.url)).setParams({
            param: {
                fileId: fileId,
                remark: remark
            },
            serviceId: "app.file.edit"
        }).do().success(function (data) {
            layer.msg('修改成功');
        });
    }
});

var downloadZip = function (url) {
    var $form = $('<form method="GET"></form>');
    $form.attr('action', url);
    $form.appendTo($('body'));
    $form.submit();
};